package org.example.springboot.service.impl;

import org.example.springboot.dao.UserDAO;
import org.example.springboot.dao.impl.UserDAOImpl;
import org.example.springboot.entity.PageEntity;
import org.example.springboot.entity.User;
import org.example.springboot.service.UserService;
import org.example.springboot.util.MD5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 业务逻辑实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDAO userDAO;

    @Override
    public User login(String username, String password) {
        //1.根据用户名查询用户信息
        User user = userDAO.selectByUsername(username);
        if(user == null){
            return null;
        }
        //用户存在再判断密码，将用户填写的密码加密后和数据库密码比较
        String pass = MD5Utils.md5(password);
        //相同就返回用户
        if(pass.equals(user.getUser_pwd())){
            return user;
        }
        return null;
    }

    @Override
    public List<User> findAll() {
        return userDAO.selectAll();
    }

    @Override
    public User findById(String userId) {
        return userDAO.selectById(userId);
    }

    @Override
    public boolean save(User user) {
        return userDAO.insert(user);
    }

    @Override
    public boolean remove(String userId) {
        return userDAO.delete(userId);
    }

    @Override
    public boolean update(User user) {
        return userDAO.update(user);
    }

    @Override
    public PageEntity<User> findUserPage(Integer current, Integer pageSize) {
        //查询总记录数
        int total = userDAO.selectUserCount();
        //查询当前页数据
        List<User> users = userDAO.selectUserLimits((current - 1) * pageSize, pageSize);
        //包装数据发送给前端
        PageEntity<User> pageEntity = new PageEntity<>();
        pageEntity.setCurrent(current);
        pageEntity.setPageSize(pageSize);
        pageEntity.setTotal(total);
        pageEntity.setRecords(users);
        return pageEntity;
    }
}
